package com.cskaoyan.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.cskaoyan.mall.commons.util.jwt.AESUtil;
import com.cskaoyan.user.constants.UserRetCode;
import com.cskaoyan.user.dal.entitys.Member;
import com.cskaoyan.user.dal.entitys.UserVerify;
import com.cskaoyan.user.dal.persistence.MemberMapper;
import com.cskaoyan.user.dal.persistence.UserVerifyMapper;
import com.cskaoyan.user.dto.UserRegisterResponse;
import com.cskaoyan.user.form.UserRegisterRequest;
import com.cskaoyan.user.form.UserVerifyRequest;
import com.cskaoyan.user.service.IUserRegisterService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author wjj
 * @date 2023-01-09 20:42
 * @describe
 */
@Slf4j
@Service
@Transactional
public class IUserRegisterServiceImpl implements IUserRegisterService {

    @Autowired
    MemberMapper memberMapper;

    @Autowired
    UserVerifyMapper userVerifyMapper;

    @Autowired
    JavaMailSender mailSender;


    @Override
    public UserRegisterResponse register(UserRegisterRequest request) {
        String uuid = UUID.randomUUID().toString();

        UserRegisterResponse userRegisterResponse = new UserRegisterResponse();
        //首先校验输入的账户密码是否为null或空格
        if (request.getUserName() == null || request.getUserName().trim().equals("")) {
            userRegisterResponse.setCode(401);
            userRegisterResponse.setMsg("用户账户名输入不合法");
        } else if (request.getEmail() == null || request.getEmail().trim().equals("")) {
            userRegisterResponse.setCode(402);
            userRegisterResponse.setMsg("用户邮箱输入不合法");
        } else if (request.getUserPwd() == null || request.getUserPwd().trim().equals("")) {
            userRegisterResponse.setCode(403);
            userRegisterResponse.setMsg("用户密码输入不合法");
        } else {
            Example example = new Example(Member.class);
            example.createCriteria().andEqualTo("username", request.getUserName());
            List<Member> memberList = memberMapper.selectByExample(example);

            Member member = new Member();
            member.setUsername(request.getUserName());
            Date date = new Date();
            member.setCreated(date);
            member.setUpdated(date);
            member.setIsVerified("N");
            member.setState(0);

            //密码加密
            AESUtil aesUtil = new AESUtil(request.getUserPwd());
            String pwd = aesUtil.encrypt();

            member.setPassword(pwd);
            member.setEmail(request.getEmail());
            //然后判断用户名是否重复

            if (memberList.size() != 0) {
                //用户名已存在
                userRegisterResponse.setCode(404);
                userRegisterResponse.setMsg(UserRetCode.USERNAME_ALREADY_EXISTS.getMessage());
            } else {
                int affectRows = memberMapper.insert(member);
                if (affectRows == 0) {
                    userRegisterResponse.setCode(405);
                    userRegisterResponse.setMsg(UserRetCode.USER_REGISTER_FAILED.getMessage());
                } else {
                    UserVerify userVerify = new UserVerify();
                    userVerify.setUsername(request.getUserName());
                    userVerify.setRegisterDate(date);
                    userVerify.setUuid(uuid);
                    userVerify.setIsExpire("N");
                    userVerify.setIsVerify("N");
                    userVerifyMapper.insert(userVerify);

                    //生成日志
                    log.info("用户注册成功,注册参数request:{}", JSON.toJSONString(request));

                    //利用多线程发送激活邮件
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            sendMail(request, uuid);
                        }
                    }).start();

                    userRegisterResponse.setCode(200);
                    userRegisterResponse.setMsg("注册成功");
                }
            }
        }
        return userRegisterResponse;
    }

    @Value("${email.text}")
    String test;

    @Value("${email.subject}")
    String subject;

    @Value("${email.fromEmail}")
    String fromEmail;

    private void sendMail(UserRegisterRequest request, String uuid){
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setSubject(subject);
        simpleMailMessage.setFrom(fromEmail);
        simpleMailMessage.setTo(request.getEmail());
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("点击链接激活账户：").append("http://localhost:8080/user/verify?uid=").append(uuid).append("&").append("username=").append(request.getUserName());
        simpleMailMessage.setText(stringBuffer.toString());
        mailSender.send(simpleMailMessage);
    }

    @Override
    public void verify(UserVerifyRequest request) {

    }
}
